package utils

import (
	"fmt"
	"strings"

	"github.com/aws/jsii-runtime-go"
)

func ConvertStringSliceToPointer(slice []string) []*string {
	result := make([]*string, len(slice))
	for i, s := range slice {
		result[i] = jsii.String(s)
	}
	return result
}

func ConvertPointerSliceToString(slice []*string) []string {
	result := make([]string, len(slice))
	for i, s := range slice {
		if s != nil {
			result[i] = *s
		}
	}
	return result
}

func SafeDereference(str *string) string {
	if str == nil {
		return ""
	}
	return *str
}

func ConvertTags(tags map[string]string) *map[string]*string {
	result := make(map[string]*string)
	for k, v := range tags {
		result[k] = jsii.String(v)
	}
	return &result
}

// GenerateResourceName 生成资源名称
func GenerateResourceName(prefix, env, purpose string) string {
	return fmt.Sprintf("%s-%s-%s", prefix, env, purpose)
}

// ValidateSubnetID 验证子网ID格式
func ValidateSubnetID(subnetID string) error {
	if !strings.HasPrefix(subnetID, "subnet-") {
		return fmt.Errorf("invalid subnet ID format: %s", subnetID)
	}
	return nil
}

// ValidateSecurityGroupID 验证安全组ID格式
func ValidateSecurityGroupID(sgID string) error {
	if !strings.HasPrefix(sgID, "sg-") {
		return fmt.Errorf("invalid security group ID format: %s", sgID)
	}
	return nil
}

// ValidateInstanceType 验证实例类型
func ValidateInstanceType(instanceType string) error {
	validTypes := []string{
		"t2.micro", "t2.small", "t2.medium", "t2.large",
		"t3.micro", "t3.small", "t3.medium", "t3.large",
		"m5.large", "m5.xlarge", "m5.2xlarge",
		"c5.large", "c5.xlarge", "c5.2xlarge",
	}

	for _, validType := range validTypes {
		if instanceType == validType {
			return nil
		}
	}

	return fmt.Errorf("invalid instance type: %s", instanceType)
}

// MergeTags 合并标签
func MergeTags(defaultTags, customTags map[string]string) map[string]string {
	result := make(map[string]string)

	// 先添加默认标签
	for k, v := range defaultTags {
		result[k] = v
	}

	// 然后添加自定义标签（会覆盖默认标签）
	for k, v := range customTags {
		result[k] = v
	}

	return result
}
